<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2017/11/29/029
 * Time: 11:36
 */

namespace app\api\service;


use think\Db;
use think\Exception;
use think\facade\Log;

Loader::import('WxPay.WxPay', EXTEND_PATH, '.Api.php');

class WxNotify {
    //<xml>
    //<appid><![CDATA[wx2421b1c4370ec43b]]></appid>
    //<attach><![CDATA[支付测试]]></attach>
    //<bank_type><![CDATA[CFT]]></bank_type>
    //<fee_type><![CDATA[CNY]]></fee_type>
    //<is_subscribe><![CDATA[Y]]></is_subscribe>
    //<mch_id><![CDATA[10000100]]></mch_id>
    //<nonce_str><![CDATA[5d2b6c2a8db53831f7eda20af46e531c]]></nonce_str>
    //<openid><![CDATA[oUpF8uMEb4qRXf22hE3X68TekukE]]></openid>
    //<out_trade_no><![CDATA[1409811653]]></out_trade_no>
    //<result_code><![CDATA[SUCCESS]]></result_code>
    //<return_code><![CDATA[SUCCESS]]></return_code>
    //<sign><![CDATA[B552ED6B279343CB493C5DD0D78AB241]]></sign>
    //<sub_mch_id><![CDATA[10000100]]></sub_mch_id>
    //<time_end><![CDATA[20140903131540]]></time_end>
    //<total_fee>1</total_fee>
    //<trade_type><![CDATA[JSAPI]]></trade_type>
    //<transaction_id><![CDATA[1004400740201409030005092168]]></transaction_id>
    //</xml>

    public function NotifyProcess($data, &$msg)
    {
        if (!array_key_exists("transaction_id", $data)) {
            $msg = "输入参数不正确";
            return false;
        }

        file_put_contents('../runtime/NotifyProcess.txt', json_encode($data));

        //查询订单，判断订单真实性
        if (!$this->Queryorder($data["transaction_id"])) {
            $msg = "订单查询失败";
            return false;
        } else {
            $pay_sn = $data["transaction_id"]; //支付单号
            $out_trade_no = $data['out_trade_no']; //订单号
            $order_price = $data['total_fee'] / 100; //订单支付金额

            // 获取商家数据包
            $attach = json_decode($data['attach'], true);
            //验证回调身份
            $des3 = new \Des3\DES3();
            if($des3->decrypt($attach['sign']) != 'eybs.com') {
                return false;
            }
            file_put_contents('../runtime/NotifyProcess.txt', "验证通过，开始回调 \n ", FILE_APPEND);
            $pay_result = \app\api\service\Pay::pay_notify($order_price, $out_trade_no, $pay_sn, 'wechat', '微信支付');
            if ($pay_result) {
                // 支付成功
                return true; // 请不要修改或删除
            } else {
                // 支付失败
                return false; // 请不要修改或删除
            }
        }
    }
}